//
//  accountDetailViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/2/23.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "accountDetailViewController.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
#import "accountViewController.h"
#import "focus_TableViewCell.h"
#import "UIViewExt.h"
#import "MJRefresh.h"
#import "accountDetailModel.h"
#import "accountDetailTableViewCell.h"
#import "userInformationViewController.h"
@interface accountDetailViewController ()<UITableViewDelegate,UITableViewDataSource,MJRefreshBaseViewDelegate>
{
    int page;
    int pages;
    UIImageView *NOFollow;
    MJRefreshSystemHeaderView *header;
    MJRefreshFooterView *footer;
}
@property (strong, nonatomic) UITableView *detailTableview;
@property (strong, nonatomic) NSMutableArray *detailArray;
@end

@implementation accountDetailViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAccount:) name:@"changeAccount" object:nil];
    }
    return self;
}
- (void)changeAccount:(NSNotification *)notification
{
    NSString *str = notification.object;
    _balance = [NSString stringWithFormat:@"%.2f",_balance.floatValue - str.floatValue];
    self.title = [NSString stringWithFormat:@"余额：¥%@", _balance];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NSString stringWithFormat:@"余额：¥%@", _balance];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    self.detailArray = [[NSMutableArray alloc] init];
    page = 1;
    [self requestDataWithUid:nil refreshing:nil page:page];
    [self createNavigationView];
}
- (void)createNavigationView
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.tag = 36;
    [leftButton setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton addTarget:self action:@selector(touchNavigationButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [rightButton setTitle:@"提现" forState: UIControlStateNormal];
//    rightButton.titleLabel.font = [UIFont systemFontOfSize:17];
//    
//    rightButton.frame = CGRectMake(0, 0, 60, 30);
//    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(rightbuttonClick) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *rightItem = []//[[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提现" style:UIBarButtonItemStylePlain target:self action:@selector(rightbuttonClick)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}
- (void)touchNavigationButton
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightbuttonClick
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    
    NSString *str = @"http://123.57.1.143/api/cash/check";
    
    NSString *_header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:_header forHTTPHeaderField:@"authorization"];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        accountViewController *accountVC = [[accountViewController alloc] init];
        accountVC.balance = _balance;
        if (![[responseObject valueForKey:@"status"] isEqualToString:@"errors"]) {
            accountVC.isPayEnable = 1;
        } else {
            accountVC.isPayEnable = 0;
        }
        [self.navigationController pushViewController:accountVC animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)createTableView
{
    self.detailTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
    _detailTableview.delegate = self;
    _detailTableview.dataSource = self;
    _detailTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _detailTableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [self.view addSubview:_detailTableview];

    header = [MJRefreshSystemHeaderView header];
    header.scrollView = _detailTableview;
    header.delegate = self;
    footer = [MJRefreshFooterView footer];
    footer.scrollView = _detailTableview;
    footer.delegate = self;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _detailArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [NSString stringWithFormat:@"foucsCell"];
    // 检查表视图中是否存在闲置的单元格
    accountDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[accountDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (_detailArray.count > 0) {
        cell.model = _detailArray[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    accountDetailModel *model = _detailArray[indexPath.row];
    //    NSLog(@"id------->%@", model.id);
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] isEqualToString:model.user_id]) {
        if (self.tabBarController.selectedIndex == 4) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
            [self.tabBarController setSelectedIndex:4];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    } else {
        userInformationViewController *userinformation = [[userInformationViewController alloc] initWithSelfUid:model.user_id];
        [self.navigationController pushViewController:userinformation animated:YES];
    }
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshSystemHeaderView class]];
    if (isHeader) {
        page = 1;
        [_detailArray removeAllObjects];
        [self requestDataWithUid:nil refreshing:refreshView page:page];
    }else {
        if (pages == 1 && page == pages) {
            footer.hidden = YES;
        } else {
            page++;
            [self requestDataWithUid:nil refreshing:refreshView page:page];
        }
    }
}

- (void)requestDataWithUid:(NSString *)uid refreshing:(MJRefreshBaseView *)refresh page:(int)pag
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *userheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:userheader forHTTPHeaderField:@"authorization"];
    NSString *fansString=[NSString stringWithFormat:@"http://123.57.1.143/api/user/getorder?p=%d",pag];
    [manager GET:fansString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [responseObject valueForKey:@"data"];
        for (NSDictionary *dict in dic) {
            accountDetailModel *followModel = [[accountDetailModel alloc] init];
            [followModel setValuesForKeysWithDictionary:dict];
            [_detailArray addObject:followModel];
            //            [_detailArray addObject:followModel];
        }
        if (_detailArray.count > 0) {
            if (_detailTableview == nil) {
                [self createTableView];
            } else {
                [_detailTableview reloadData];
            }
        } else {
        }
        if ( [responseObject valueForKey:@"meta"] == nil || pages == 1) {
            footer.hidden = YES;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refresh endRefreshing];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
